import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class CurveFit extends FitnessFunction
{
	int size;
	int[] testX;
	// int [] testY;

	// changed by senglee - test data could be float
	double[] testY;

	public CurveFit() throws NumberFormatException, IOException
	{

		name = "Curve Fitting Problem";
		// Create Table of X values from input file
		Scanner input = new Scanner(
				new FileReader(Parameters.dataInputFileName));
		size = input.nextInt();
		testX = new int[size];
		testY = new double[size];
		for (int i = 0; i < size; i++) {
			testX[i] = input.nextInt();
			testY[i] = input.nextDouble(); // changed by senglee - test data
											// could be float
		}
		input.close();
	}

	@Override
	public void doRawFitness(Chromo X)
	{
		double difference = 0;
		double esty = 0;
		for (int z = 0; z < size; z++) {
			esty = (X.chromofloat[0] * Math.pow(testX[z], 2))
					+ (X.chromofloat[1] * testX[z]) + X.chromofloat[2]
					+ (X.chromofloat[3] * Math.sin(testX[z]))
					+ (X.chromofloat[4] * Math.cos(testY[z]));
			if (esty != 0) {
				difference = Math.abs((testY[z] - esty));
			} else {
				difference = Double.MAX_VALUE;
			}
			X.rawFitness = X.rawFitness + difference;
		}
		X.rawFitness = X.rawFitness / size;
	}

	@Override
	public void doPrintGenes(Chromo X, FileWriter output)
			throws java.io.IOException
	{

		Hwrite.right((int) X.rawFitness, 13, output);

		output.write("\nGene: ");
		for (int i = 0; i < Parameters.geneSize; i++) {
			Hwrite.rightFloat(X.chromofloat[i], output);
		}

		output.write("\n\n");
		return;
	}
}
